package com.miyake.rest.comm;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.miyake.rest.StreamToByteConverter;


public abstract class AbstractHttpPost {
	private byte[] receivedData;
    private String url;
    private String responseContentType;
	public AbstractHttpPost(String url, byte[] sendData) {
	    this.url = url;
	    post(sendData);
	}
	
    protected void post(byte[] sendData) {
        try {
	    	  // Connect to server
	    	  URL urlObj = new URL(url);          
	    	  HttpURLConnection http = (HttpURLConnection)urlObj.openConnection();          
	    	  http.setRequestMethod("POST");          
	    	  
	    	  http.setRequestProperty("Content-Type", getContentType());          
	    	  
	    	  http.setDoInput(true);          
	    	  http.setDoOutput(true);          
	    	  http.setUseCaches(false);   
	    	  http.setReadTimeout(60*1000);
	    	  http.setConnectTimeout(60*1000);

	    	  http.connect();
	    	  
	    	  // Post data       
	    	  OutputStream out = new BufferedOutputStream(http.getOutputStream()); 
	    	  out.write(sendData);  
	    	  out.flush();     
	    	  
	    	  // Receive response
	    	  InputStream in = new BufferedInputStream(http.getInputStream());      
	    	  setResponseContentType(http.getContentType());
	    	  this.setReceivedData(new StreamToByteConverter(in).get());
	    	  //BufferedReader reader = new BufferedReader(new InputStreamReader(in));       
	    	  
	    	  // close
	    	  //reader.close();          
	    	  in.close();          
	    	  out.close();          
	    	  http.disconnect();       
	      }       
	      catch(Exception e) {          
	          e.printStackTrace();
	      }
    }

    protected abstract String getContentType();
//	protected abstract byte[] getPostData();

    /**
     * @return the receivedData
     */
    public byte[] getReceivedData() {
        return receivedData;
    }

    /**
     * @param receivedData the receivedData to set
     */
    public void setReceivedData(byte[] receivedData) {
        this.receivedData = receivedData;
    }

    /**
     * @return the responseContentType
     */
    public String getResponseContentType() {
        return responseContentType;
    }

    /**
     * @param responseContentType the responseContentType to set
     */
    public void setResponseContentType(String responseContentType) {
        this.responseContentType = responseContentType;
    }
}
